import { PureComponent } from 'react';
import {
  Scene, OrthographicCamera, BoxGeometry, Line, Vector3,
  Mesh, WebGLRenderer, MeshBasicMaterial, PointLight,
  MeshLambertMaterial
} from 'three';

const drawAxes = scene => {
  const xGeo = new BoxGeometry();
  const xGeoPoints = [
    new Vector3(0, 0, 0),
    new Vector3(6, 0, 0)
  ];
  xGeo.setFromPoints(xGeoPoints);
  const xMat = new MeshBasicMaterial({
    color: 0xff0000
  });
  const xAxis = new Line(xGeo, xMat);
  scene.add(xAxis);

  const yGeo = new BoxGeometry();
  const yGeoPoints = [
    new Vector3(0, 0, 0),
    new Vector3(0, 6, 0)
  ];
  yGeo.setFromPoints(yGeoPoints);
  const yMat = new MeshBasicMaterial({
    color: 0x00ff00
  });
  const yAxis = new Line(yGeo, yMat);
  scene.add(yAxis);

  const zGeo = new BoxGeometry();
  const zGeoPoints = [
    new Vector3(0, 0, 0),
    new Vector3(0, 0, 6)
  ];
  zGeo.setFromPoints(zGeoPoints);
  const zMat = new MeshBasicMaterial({
    color: 0x00ccff
  });
  const zAxis = new Line(zGeo, zMat);
  scene.add(zAxis);
};

const scene = new Scene();

drawAxes(scene);

let renderer = null;

const camera = new OrthographicCamera(-5, 5, 3.75, -3.75, 0.1, 100);
camera.position.set(5, 15, 25);
camera.lookAt(0, 0, 0);

const light = new PointLight(0xffffff, 2, 100);
light.position.set(0, 1.5, 2.5);
scene.add(light);

const leftGeo = new BoxGeometry(2, 2, 2);
const leftGeoMat = new MeshLambertMaterial({
  color: 0xffffff
});
const leftMesh = new Mesh(leftGeo, leftGeoMat);
leftMesh.position.x = -3;
scene.add(leftMesh);

const rightGeo = new BoxGeometry(2, 2, 2);
const rightGeoMat = new MeshLambertMaterial({
  color: 0x00ff00
});
const rightMesh = new Mesh(rightGeo, rightGeoMat);
rightMesh.position.x = 3;
scene.add(rightMesh);

const changeLightPosition = () => {
  /**
  * 调整光照位置之后我们发现了明显的明暗变化,
  * 这也表现了点光源的特质: 光线由一个点发出, 同时造成了渐变的效果
  * 
  * 物体渲染的材质颜色不变, 但是局部有了明暗的变化
  */
  light.position.set(0, 15, 25);
  renderer.render(scene, camera);
};

const resetLightPosition = () => {
  /**
  * 为了有对比, 这里我将y z轴的数值缩小到了原来的10倍
  */
  light.position.set(0, 1.5, 2.5);
  renderer.render(scene, camera);
};

class Index extends PureComponent {

  componentDidMount() {
    renderer = new WebGLRenderer({
      canvas: document.getElementById('mainCanvas')
    });
    renderer.render(scene, camera);

  }

  render() {

    return (
      <div>
        <div>
          <button
            onClick={resetLightPosition}
          >重置位置</button>
          <button
            onClick={changeLightPosition}
          >变更位置</button>
        </div>
        <canvas
          id="mainCanvas"
          width="400"
          height="300"
        />
      </div>
    );
  }
}

export default Index;